package com.dl.mall.controller.user;

import com.dl.mall.config.satoken.StpUserUtil;
import com.dl.mall.utils.CaptchaUtils;
import com.dl.mall.utils.IPUtils;
import com.dl.mall.utils.RedisUtils;
import com.dl.mall.utils.result.Info;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author DL
 * @create 2022-03-19 13:24
 */
@Slf4j
@RestController()
@RequestMapping("/common")
@Api(tags="通用controller")
public class CommonController {

    @Resource
    private RedisUtils redisUtils;

    @ApiOperation(value="获得验证码图片")
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        //设置验证码位数
        String captcha = CaptchaUtils.generateVerifyCode(4);
        //验证码放入session
        //session.setAttribute(Info.SESSION_CAPTCHA.getValue(), captcha);

        String ipAddr = IPUtils.getIpAddr(request);
        System.out.println("ipAddr = " + ipAddr);
        redisUtils.set(ipAddr, captcha, 60);
        try {
            //获得输出流
            ServletOutputStream os = response.getOutputStream();
            //设置响应头
            response.setContentType("image/png");
            //response.setContentType("application/octet-stream");
            //获得验证码图片ConstantUtils.SESSION_Captcha.getValue()
            CaptchaUtils.outputImage(150,60, os, captcha);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
